package com.mdd.service.impl;

import com.mdd.common.CustomException;
import com.mdd.pojo.Dish;
import com.mdd.pojo.Setmeal;
import com.mdd.pojo.vo.DishVo;
import com.mdd.pojo.vo.SalesTopVo;
import com.mdd.pojo.vo.SetmealVo;
import com.mdd.service.*;
import javafx.util.Pair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class TopServiceImpl implements TopService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public SalesTopVo getSalesTop(Integer type) {
        Integer nType = Optional.ofNullable(type).orElse(0);
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        //拼接key
        String key = "top:"+(nType==0? "dish:":"setmeal:")+"total";
        //获取销量信息
        Set<ZSetOperations.TypedTuple<String>> rangeWithScores = zSetOperations.reverseRangeWithScores(key, 0, 20);
        if (rangeWithScores == null || rangeWithScores.size() == 0) {
            throw new CustomException("服务器内部出现问题");
        }
        //处理原数据
        List<Pair<Long, Long>> topList = rangeWithScores.stream().map(o -> {
            return new Pair<Long, Long>(Long.parseLong(o.getValue()), o.getScore().longValue());
        }).collect(Collectors.toList());
        //获取销量榜信息
        SalesTopVo salesTopVo = new SalesTopVo();
        List<DishVo> dishVos = null;
        List<SetmealVo> setmealVos = null;
        if (nType != 1) {
           dishVos = topList.stream().map(o -> {
                //说明为菜品榜
                Dish byId = dishService.getById(o.getKey());
                DishVo dishVo = new DishVo();
                BeanUtils.copyProperties(byId, dishVo);
                dishVo.setSale(o.getValue());
                return dishVo;
            }).collect(Collectors.toList());
        }else {
            setmealVos = topList.stream().map(o -> {
                //说明为菜品榜
                Setmeal byId = setmealService.getById(o.getKey());
                SetmealVo setmealVo = new SetmealVo();
                BeanUtils.copyProperties(byId, setmealVo);
                setmealVo.setSale(o.getValue());
                return setmealVo;
            }).collect(Collectors.toList());
        }
        salesTopVo.setSetmealVos(setmealVos);
        salesTopVo.setDishVos(dishVos);
        return salesTopVo;
    }
}
